<?php ?>

<div>
	<form method="POST" action="create_record">
		<label>New record</label><br>
		<input type = "text" data-bind="value:newrec.table1"><br>
		<input type = "text" data-bind="value:newrec.table2"><br>
		<input type = "text" data-bind="value:newrec.table3"><br>
		<input type = "text" data-bind="value:newrec.table4"><br>
		<button data-bind="click:savenewrec"> Add </button>
	</form>
</div>
<table>
	<thead>
		<tr data-bind="foreach:table().model.head">
			<th data-bind="text:$data"></th>
		</tr>
	</thead>
	<tbody data-bind="foreach:table().model.body">
		<tr data-bind="foreach:$data">
			<td data-bind="text:$data"></td>
		</tr>		
	</tbody>
</table>

<script src="http://yandex.st/jquery/2.1.0/jquery.min.js"></script>
<script src="http://yandex.st/lodash/2.4.1/lodash.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script>
<script src="wp-content/plugins/js/knockout.mapping-latest.js"></script>

<script>
	var dm_string = <?php  echo json_encode($table1); ?>;
	var adminurl = "<?php  echo admin_url('admin-ajax.php'); ?>";
	var ajaxurl = ajaxurl || adminurl;
	console.log(abspath);
</script>

<script>
	function TableModel(data, parent){
		var self = this;
		console.log(data);
		self.model = {};
		self.model.head = ko.observableArray(data.head);
		self.model.body = ko.observableArray(data.body);	
		console.log(self.model.body());
	}

	function NewFormModel(data,parent){
		var self = this;
		self.model = ko.mapping.fromJS(data);
	}

	function ViewModel(data){
		var self = this;
		self.table = ko.observable( new TableModel( data, self ));
		self.newrec = {
			table1: ko.observable(''),
			table2: ko.observable(''),
			table3: ko.observable(''),
			table4: ko.observable('')
		};
		
		self.savenewrec = function(){
			var newr = {
				table_name:"test_table",
				values:[self.newrec.table1(),
						self.newrec.table2(),
						self.newrec.table3(),
						self.newrec.table4()]
			};

			console.log( ajaxurl + "?action=zakaz_zvonka" );
			console.log(newr);
			self.table().model.body();
			var push = newr.values;
			push.id = ' ';
			self.table().model.body.push(push);
		    jQuery.ajax({
		         type : "post",
		         dataType : "json",
		         url : ajaxurl + "?action=zakaz_zvonka",
		         data : newr})
		        .done(	 function(response) {
       		            newr.id = response.id;
       		            
       		           	self.newrec.table1('');
       					self.newrec.table2('');
       					self.newrec.table3('');
       					self.newrec.table4('');
     		         });
			
	       }
			
		}
		
	
	$(function(){
		var DATA_MODEL = JSON.parse( _.unescape(dm_string) );	
		ko.applyBindings(new ViewModel(DATA_MODEL));
	});
</script>
